#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "msg.h"

int write_remote_log(int sockfd);

int main(int argc, char **argv)
{
	int sockfd;
	struct sockaddr_in saddr;
	int ret;

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) {
		perror("socket()");
		exit(1);
	}

	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(5120);
	ret = inet_pton(AF_INET, argv[1], &saddr.sin_addr);
	if (ret != 1) {
		if (ret == 0) {
			printf("Wrong IP format.\n");
		} else {
			perror("inet_pton()");
		}
		exit(1);
	}

	ret = connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
	if (ret == -1) {
		perror("connect()");
		exit(1);
	}

	ret = write_remote_log(sockfd);

	exit(0);
}

int write_remote_log(int sockfd)
{
	//printf("Write remote log.\n");
	time_t tm;
	char *str;
	struct msg_host_opt_st *opt;
	int ret, pos, len;

	tm = time(NULL);
	if (tm == -1) {
		perror("time()");
		return -1;
	}
	str = "thunder";
	opt = malloc(sizeof(*opt) + strlen(str) + 1);
	if (opt == NULL) {
		return -1;
	}

	memset(opt, 0, sizeof(*opt) + strlen(str) + 1);
	opt->time = htonl((uint32_t)tm);
	opt->opt = OPT_RUN;
	opt->offset = htonl(strlen(str) + 1);
	opt->data[0] = OPT_OPEN;
	memcpy(&opt->data[1], str, strlen(str) + 1);
	printf("memcpy:%s,%s:%d\n", str, &opt->data[1], strlen(str));

	len = sizeof(*opt) + strlen(str) + 1;
	pos = 0;
	while (len > 0) {
		ret = write(sockfd, opt + pos, len);
		if (ret == -1) {
			perror("write()");
			free(opt);
			return -1;
		}
		len -= ret;
		pos += ret;
	}

	//
	struct tm *t;
	t = localtime((time_t *)&opt->time);
	printf("时间：%d/%d/%d %d:%d:%d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
	printf("opt:%d\t%d\n", opt->opt, opt->data[0]);
	printf("action:%s\n", &opt->data[1]);

	free(opt);

	return 0;
}

